package com.gitee.feizns.quickstart.mybatis.flex.validation.validator;

import com.gitee.feizns.dynamic.Lists;
import com.gitee.feizns.dynamic.Objs;
import com.gitee.feizns.quickstart.mybatis.flex.validation.constraints.Exist;
import com.gitee.feizns.quickstart.validation.validator.AbstractConstraintValidator;
import com.mybatisflex.core.query.QueryChain;

import javax.validation.ConstraintValidatorContext;
import java.io.Serializable;
import java.util.List;

/**
 * 存在指定的ID
 * @author feizns
 * @since 2023/2/5
 */
public class ExistsConstraintValidator extends AbstractConstraintValidator<Exist, Object> {

    /**
     * 账号正则
     */
    private Exist annotation;

    @Override
    public void initialize(Exist annotation) {
        super.initialize(annotation);
        this.annotation = annotation;
    }

     @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        List<Serializable> values = Lists.of(Objs.cast(Objs.toArray(o), Serializable[]::new));
        if ( values != null && values.size() == 1 )
            return QueryChain.of(annotation.type()).eq(annotation.field(), values.get(0)).count() > 0;
        else if ( values != null && values.size() > 1 )
            return QueryChain.of(annotation.type()).in(annotation.field(), values).count() == values.size();
        return false;
    }

}